package com.agile.leetcode.AESandRSAandMd5;

import javax.crypto.Cipher;
import java.security.*;
import java.util.Base64;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/18 10:08
 */
public class KeyUtil {
    private static KeyPair keyPair;

    static {
        try {
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            // 获取随机值种子
            SecureRandom secureRandom = new SecureRandom(String.valueOf(System.currentTimeMillis()).getBytes());
            keyPairGenerator.initialize(2048, secureRandom);
            keyPair = keyPairGenerator.generateKeyPair();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取公钥
     *
     * @return
     */
    public static String getPublicKey() {
        PublicKey publicKey = keyPair.getPublic();
        byte[] encoded = publicKey.getEncoded();
        return Base64.getEncoder().encodeToString(encoded);
    }

    /**
     * 获取私钥
     *
     * @return
     */
    public static String getPrivateKey() {
        PrivateKey privateKey = keyPair.getPrivate();
        byte[] encoded = privateKey.getEncoded();
        return Base64.getEncoder().encodeToString(encoded);
    }

    /**
     * 公钥加密
     *
     * @param content
     * @param publicKey
     * @return
     */
    public static byte[] encryptWithPublicKey(byte[] content, PublicKey publicKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            // 加密
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] bytes = cipher.doFinal(content);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 私钥解密
     *
     * @param content
     * @param privateKey
     * @return
     */
    public static byte[] decryptWithPrivateKey(byte[] content, PrivateKey privateKey) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] bytes = cipher.doFinal(content);
            return bytes;
        } catch (Exception e) {

        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(KeyUtil.getPublicKey());
        System.out.println("===============================");
        System.out.println(KeyUtil.getPrivateKey());
        // 加密
        byte[] encrypt = encryptWithPublicKey("czk".getBytes(), keyPair.getPublic());
        System.out.println(new String(encrypt));
        System.out.println("-------------------------------");
        System.out.println(new String(decryptWithPrivateKey(encrypt, keyPair.getPrivate())));
    }
}
